import { useState, Suspense, useMemo, useEffect } from "react";
import { useRoutes, useLocation, useNavigate, NavLink } from "react-router-dom";
import {
  Radio,
  Space,
  Input,
  DatePicker,
  Button,
  Toast,
  Form,
} from "antd-mobile";
import { userInfo, userUpdate, userRpwd } from "../../api/user";
import user from "../../store/user";
import style from "./style.module.scss";
import axios from "axios";
const {
  info,
  info_gender,
  info_username,
  info_age,
  info_identity,
  info_nickname,
  info_button,
  info_password,
} = style;
const Mine = () => {
  const navigate = useNavigate();
  const now = new Date();
  const [uesrInfo, setUserInfo] = useState<any>([]);
  const [gender, setGender] = useState("");
  const [visible, setVisible] = useState(false);
  const [valueDate, setValueDate] = useState<Date>();
  const [userAge, setUserAge] = useState<number>();
  const [userNickname, setUserNickname] = useState("");
  const [flag, setFlag] = useState(true);
  const sexChange = (value: any) => {
    setGender(value);
  };
  const getUserInfo = async () => {
    let res = await userInfo(user.profile.id as any);
    console.log(res);
    setUserInfo(res.data.info);
    setGender(res.data.info?.gender);
    setUserAge(res.data.info?.age);
    setUserNickname(res.data.info?.nickname);
  };
  const getUserUpdate = async () => {
    const obj = {
      id: user.profile.id as any,
      age: ageVal,
      gender: gender,
      nickname: userNickname,
    };
    console.log(obj);
    let res = await userUpdate(obj);
    console.log(res);
    Toast.show(res.data.message);
  };
  const onFinish = async (value: any) => {
    // console.log(value);
    let obj = {
      ...value,
      id: user.profile.id,
    };
    let res = await userRpwd(obj);
    console.log(res);
    if (res.data.code === 1) {
      Toast.show(res.data.message);
      navigate("/login");
    } else {
      Toast.show(res.data.message);
    }
  };
  const setLogout = async () => {
    let res = await user.LOG_OUT(user.profile.id);
    console.log(res);
    if (res.data.code === 1) {
      Toast.show(res.data.message);
      navigate("/login");
    } else {
      Toast.show(res.data.message);
    }
  };
  const ageVal = useMemo(() => {
    let num = (new Date() as any) - (new Date(valueDate as Date) as any);
    let age = Math.floor(num / 31536000000);
    return age;
  }, [visible]);
  useEffect(() => {
    getUserInfo();
  }, []);

  return (
    <>
      {user.profile.token ? (
        <div className={info}>
          {flag ? (
            <>
              <div className={info_username}>
                <Input
                  placeholder="请输入内容"
                  value={"用户名：" + uesrInfo.username}
                  readOnly
                />
              </div>
              <div className={info_age}>
                <Input
                  placeholder="请输入内容"
                  value={`年龄：${ageVal ? ageVal : userAge}`}
                  readOnly
                />
                <Button
                  onClick={() => {
                    setVisible(true);
                  }}
                >
                  选择
                </Button>
                <DatePicker
                  title="时间选择"
                  visible={visible}
                  onClose={() => {
                    setVisible(false);
                  }}
                  max={now}
                  onConfirm={(val) => {
                    setValueDate(val);
                    Toast.show(val.toDateString());
                  }}
                />
              </div>
              <div className={info_gender}>
                <Input placeholder="请输入内容" value="性别：" readOnly />
                <Radio.Group
                  value={gender}
                  onChange={(value) => sexChange(value)}
                >
                  <Space direction="vertical">
                    <Radio value="男">男</Radio>
                    <Radio value="女">女</Radio>
                  </Space>
                </Radio.Group>
              </div>
              <div className={info_identity}>
                <span style={{ fontSize: 17 }}>身份：</span>
                <Input
                  placeholder="请输入内容"
                  value={uesrInfo.identity}
                  style={{ borderBottom: "1px solid black" }}
                />
              </div>
              <div className={info_nickname}>
                <span style={{ fontSize: 17 }}>昵称：</span>
                <Input
                  placeholder="请输入内容"
                  value={userNickname}
                  style={{ borderBottom: "1px solid black" }}
                  onChange={(value) => {
                    setUserNickname(value);
                  }}
                />
              </div>
              <div className={info_button}>
                <Button onClick={() => getUserUpdate()}>修改信息</Button>
                <Button
                  onClick={() => {
                    setFlag(false);
                  }}
                >
                  修改密码
                </Button>
              </div>
              <Button
                block
                style={{ marginTop: 10 }}
                onClick={() => setLogout()}
              >
                退出登录
              </Button>
            </>
          ) : (
            <div className={info_password}>
              <Form
                onFinish={onFinish}
                style={{ width: "80vw" }}
                layout="horizontal"
                footer={
                  <div
                    style={{ display: "flex", justifyContent: "space-around" }}
                  >
                    <Button type="submit" color="danger">
                      修改密码
                    </Button>
                    <Button
                      onClick={() => {
                        setFlag(true);
                      }}
                    >
                      个人资料
                    </Button>
                  </div>
                }
              >
                <Form.Item
                  name="oldPassword"
                  rules={[{ required: true, message: "原始密码" }]}
                >
                  <Input onChange={console.log} placeholder="请输入原始密码" />
                </Form.Item>
                <Form.Item
                  name="newPassword"
                  rules={[
                    { required: true, message: "请输入新密码" },
                    ({ getFieldValue }) => ({
                      validator(rule, value) {
                        if (getFieldValue("oldPassword") === value) {
                          return Promise.reject("新密码与旧密码不能一致");
                        }
                        return Promise.resolve();
                      },
                    }),
                  ]}
                >
                  <Input onChange={console.log} placeholder="请输入新密码" />
                </Form.Item>
                <Form.Item
                  name="rNewPassword"
                  rules={[
                    { required: true, message: "请与新密码一致" },
                    ({ getFieldValue }) => ({
                      validator(rule, value) {
                        if (!value || getFieldValue("newPassword") === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject("新密码与确认新密码不同！");
                      },
                    }),
                  ]}
                >
                  <Input onChange={console.log} placeholder="请重复新密码" />
                </Form.Item>
              </Form>
            </div>
          )}
        </div>
      ) : (
        <div style={{ fontSize: 20 }}>请登录后再查看</div>
      )}
    </>
  );
};

export default Mine;
